let jwt = require('./jwt');
let { ERROR } = require('./result');

//登录拦截中间件
function intercept() {
    return (req, res, next) => {

        let {token}=req.query;//获取token
        if(token==''||token==undefined){
            ERROR(res,'请输入token',null);
        }
        //根据token获取header、playload和签名
        let [header, playload, sig] = token.split('.');

        let newToken = jwt.generator(header, playload);//生成新的token
        //判断token是否被篡改
        if (newToken == token) {
            // console.log('正确的token');
            let { exp } = jwt.base64ToJson(playload);//获取过期时间
            //判断token是否过期
            if (exp < Date.now()) {
                ERROR(res,'登录过期，请重新登录',null);
            } else {                
                next();
            }
        } else {
            ERROR(res,'token被篡改',null);
        }
    };
}




module.exports = intercept;